/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package proyecto.so1;

import gramaticas.lex_sgbd;
import java.net.*;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Antonio
 */
public class comandos {


/////////////////////////////////////////////////////////////////METODOS DE SGBD
    

/////////////////////////////////////////////////////////////////////////// SEND
    public static void send (String envio, String compu)
    {
        envio=envio.substring(1,envio.length()-1);
        if(envio.length()<300){
        if(compu.equalsIgnoreCase("PC1")||compu.equalsIgnoreCase("PC2")||compu.equalsIgnoreCase("PC3"))
        {   
            SendMSG msg = new SendMSG(envio);
            ActivateMSG acmsg = new ActivateMSG();
            if(compu.equalsIgnoreCase("PC1")){                                
                msg.start();
                acmsg.start();
            }else if(compu.equalsIgnoreCase("PC2")){                               
                msg.start();
                acmsg.start();
            }else if(compu.equalsIgnoreCase("PC3")){                                
                msg.start();
                acmsg.start();
            }
        
        }else{
        JOptionPane.showMessageDialog(null,"Computadora no existente");
        }
        
        }else{
        
        JOptionPane.showMessageDialog(null,"El Tamaño del texto es mayor a 300 caracteres");
        }      
        
        
        
    //JOptionPane.showMessageDialog(null,""+envio);
    }

/////////////////////////////////////////////////////////////////////////// TYPE
    public static void type (String tablaname)
    {

    //JOptionPane.showMessageDialog(null,""+tablaname);

     if(verifica_ex("/var/grupo7/"+tablaname)){
         
         
         int num_col=numero_columnas("/var/grupo7/"+tablaname);
         if(num_col>0){
             crear_frame_mostrar(num_col,"/var/grupo7/"+tablaname);
                 //JOptionPane.showMessageDialog(null,"numero: "+num_col);
         }else{
         JOptionPane.showMessageDialog(null,"TABLA VACIA");
         }
         
     }else{
          JOptionPane.showMessageDialog(null,"Tabla no existente");
     }
    }

/////////////////////////////////////////////////////////////////////////// LOAD
    public static void load (String direccion, String tabla)
    {
    JOptionPane.showMessageDialog(null,""+direccion+" "+tabla);
    }

///////////////////////////////////////////////////////////////////// CHANGEMODE
     public static void changemode ()
    {                
        if(principal.rb1.isSelected())
        {
            principal.rb1.setSelected(false);
            principal.rb2.setSelected(true);
        }else{
              principal.rb1.setSelected(true);
              principal.rb2.setSelected(false);
             }        
    }
     
//////////////////////////////////////////////////////////////////// METODOS SQL



/////////////////////////////////////////////////////////////////////////// DROP YA
      public static void drop (String tabla)
    {
          //BORRA LA TABLA
          File fichero = new File("/var/grupo7/"+tabla);
          File aux = new File("/var/grupo7/~"+tabla);
          String cadena="";
           try {
           FileInputStream fis = new FileInputStream(fichero);
           BufferedInputStream bis = new BufferedInputStream(fis);
           DataInputStream dis = new DataInputStream(bis);
                while (dis.available() != 0)  {
                cadena+=dis.readLine()+"\n";
                }
                fis.close();    bis.close();      dis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
          if(verifica_ex("/var/grupo7/"+tabla)){
          try {            
            PrintWriter fileOut = new PrintWriter(new FileWriter(aux, false));
            fileOut.write(cadena);
            fileOut.close();            
        } catch (FileNotFoundException ex) {           
        } catch (IOException ex) {           
        }                              
          if (fichero.delete())
          {
              JOptionPane.showMessageDialog(null,"Se elimino la Tabla: "+tabla);
              System.out.println("El fichero ha sido borrado satisfactoriamente");
          }
            else{
              System.out.println("El fichero no puede ser borrado");
              JOptionPane.showMessageDialog(null,"Tabla no existente");
            }                    
          }else{          
           JOptionPane.showMessageDialog(null,"Tabla no existente");
          }
    }

///////////////////////////////////////////////////////////////////////// DELETE
      public static void delete (String tablaname)
    {
          //BORRA LOS CAMPOS DE LA TABLA  "/var/grupo7"
    //JOptionPane.showMessageDialog(null," "+tablaname);
    if(verifica_ex("/var/grupo7/"+tablaname)){
        eliminar_campos("/var/grupo7/"+tablaname);
        
    }else{
          JOptionPane.showMessageDialog(null,"Tabla no existente");
     }

    }

///////////////////////////////////////////////////////////////////////// SELECT
      public static void select (String columna , String tablaname)
    {
          
//    JOptionPane.showMessageDialog(null," "+columna+" "+tabla);
          if(verifica_ex("/var/grupo7/"+tablaname)){
         int num_col=numero_columnas("/var/grupo7/"+tablaname);
             if(num_col>0){
                 crear_frame_select(columna,"/var/grupo7/"+tablaname);
                     //JOptionPane.showMessageDialog(null,"numero: "+num_col);
             }else{
             JOptionPane.showMessageDialog(null,"TABLA VACIA");
             }

     }else{
          JOptionPane.showMessageDialog(null,"Tabla no existente");
     }

    }
      
      

///////////////////////////////////////////////////////////////////////// COMMIT
        public static void commit ()
    {
        principal.Commit();

    }

/////////////////////////////////////////////////////////////////////// ROLLBACK
            public static void rollback ()
    {


    }

////////////////////////////////////////////////////////////////////// CREATEUNO
            public static void createuno(String tabla, String dato, String tipo)
            {
            //JOptionPane.showMessageDialog(null,"Tabla "+tablaname+" dato: "+dato+" tipo: "+tipo);

          File fichero = new File("/var/grupo7/"+tabla);          
          String cadena="";
          cadena+=""+dato+"|°\n";
          cadena+=""+tipo+"|°\n";
          if(!verifica_ex("/var/grupo7/"+tabla)){
          try {
            PrintWriter fileOut = new PrintWriter(new FileWriter(fichero, false));
            fileOut.write(cadena);
            fileOut.close();
        } catch (FileNotFoundException ex) {
        } catch (IOException ex) {
        }
          }else{
           JOptionPane.showMessageDialog(null,"Tabla Repetida");
          }

 }
////////////////////////////////////////////////////////////////////// CREATEDOS
             public static void createdos(String tabla, String dato1, String tipo1, String dato2, String tipo2)
            {
//            JOptionPane.showMessageDialog(null,"Tabla "+tablaname+" dato: "+dato1+" tipo: "+tipo1);
                //create table edwin (id integer(10), nombre varchar(20))
            File fichero = new File("/var/grupo7/"+tabla);          
          String cadena="";
          cadena+=""+dato1+" | "+dato2+" |°\n";
          cadena+=""+tipo1+" | "+tipo2+" |°\n";
          if(!verifica_ex("/var/grupo7/"+tabla)){
          try {
            PrintWriter fileOut = new PrintWriter(new FileWriter(fichero, false));
            fileOut.write(cadena);
            fileOut.close();
        } catch (FileNotFoundException ex) {
        } catch (IOException ex) {
        }
          }else{
           JOptionPane.showMessageDialog(null,"Tabla Repetida");
          }


            }
///////////////////////////////////////////////////////////////////// CREATETRES
              public static void createtres(String tabla, String dato1, String tipo1, String dato2, String tipo2, String dato3, String tipo3)
            {
            //JOptionPane.showMessageDialog(null,"Tabla "+tablaname+" dato: "+dato1+" tipo: "+tipo2+" dato2: "+dato2+" tipo2: "+tipo2+" dato3: "+dato3+" tipo: "+tipo3);
             File fichero = new File("/var/grupo7/"+tabla);          
          String cadena="";
          cadena+=""+dato1+" | "+""+dato2+" | "+dato3+" |°\n";
          cadena+=""+tipo1+" | "+""+tipo2+" | "+tipo3+" |°\n";
          if(!verifica_ex("/var/grupo7/"+tabla)){
          try {
            PrintWriter fileOut = new PrintWriter(new FileWriter(fichero, false));
            fileOut.write(cadena);
            fileOut.close();
        } catch (FileNotFoundException ex) {
        } catch (IOException ex) {
        }
          }else{
           JOptionPane.showMessageDialog(null,"Tabla Repetida");
          }


            }
               public static void update(String tablaname, String set, String val)
            {
            JOptionPane.showMessageDialog(null,"Tabla "+tablaname+" set: "+set+" val: "+val);

            }
                 public static void insert_uno(String tabla, String col1, String val1)
            {
                if(val1.charAt(0)=='\"'){
               
                val1=val1.substring(1,val1.length()-1);
                }
                
                //insert into alberto (nombre) values ("hola")
            //JOptionPane.showMessageDialog(null,"Tabla "+tablaname+" set: "+col1+" val: "+val1);
             File fichero = new File("/var/grupo7/"+tabla);                                          
          File aux = new File("/var/grupo7/"+tabla);
          String cadena="";
           try {
           FileInputStream fis = new FileInputStream(fichero);
           BufferedInputStream bis = new BufferedInputStream(fis);
           DataInputStream dis = new DataInputStream(bis);
                while (dis.available() != 0)  {
                cadena+=dis.readLine()+"\n";
                }
                 cadena+=""+val1+" | °";          
                fis.close();    bis.close();      dis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
          if(verifica_ex("/var/grupo7/"+tabla)){
          try {            
            PrintWriter fileOut = new PrintWriter(new FileWriter(aux, false));
            fileOut.write(cadena);
            fileOut.close();            
        } catch (FileNotFoundException ex) {           
        } catch (IOException ex) {           
        }                                        
          }else{          
           JOptionPane.showMessageDialog(null,"Tabla no existente");
          }
          
            }
                 
public boolean revisar(String tabla){
boolean entro=false;
boolean aux=false;
boolean aux2=false;

for(int i=0; i<principal.states.size();i++){
    
    principal.table=principal.states.get(i);

    aux= Boolean.parseBoolean(principal.table.get(1).toString());
    if(!aux){
    SendState sta= new SendState(i);
    //OPERTACION

    principal.table.set(2,true);
    principal.table.set(1,true);
    principal.states.set(i,principal.table);
    }else{
        aux2= Boolean.parseBoolean(principal.table.get(2).toString()); //LOCAL
        if(aux2){
            //OPERTACION
                
        }else{
         JOptionPane.showMessageDialog(null,"Tabla Bloqueada");
        }

    }

}


return entro;

}                 
                 
                 public static void insert_dos(String tabla, String col1, String col2, String val1, String val2)
            {                                        
                if(val1.charAt(0)=='\"'){              
                val1=val1.substring(1,val1.length()-1);
                }                
          File fichero = new File("/var/grupo7/"+tabla);                                          
          File aux = new File("/var/grupo7/"+tabla);
          String cadena="";
           try {
           FileInputStream fis = new FileInputStream(fichero);
           BufferedInputStream bis = new BufferedInputStream(fis);
           DataInputStream dis = new DataInputStream(bis);
                while (dis.available() != 0)  {
                cadena+=dis.readLine()+"\n";
                }
                 cadena+=""+val1+" | "+val2+" | °";          
                fis.close();    bis.close();      dis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
          if(verifica_ex("/var/grupo7/"+tabla)){
          try {            
            PrintWriter fileOut = new PrintWriter(new FileWriter(aux, false));
            fileOut.write(cadena);
            fileOut.close();            
        } catch (FileNotFoundException ex) {           
        } catch (IOException ex) {           
        }                                        
          }else{          
           JOptionPane.showMessageDialog(null,"Tabla no existente");
          }

            }
                 public static void insert_tres(String tabla, String col1, String col2, String col3, String val1, String val2, String val3)
            {
            //JOptionPane.showMessageDialog(null,"Tabla "+tablaname+" set: "+col1+" val: "+val1);
            if(val1.charAt(0)=='\"'){
              
                val1=val1.substring(1,val1.length()-1);
                }
                
                //insert into alberto (nombre) values ("hola")
            //JOptionPane.showMessageDialog(null,"Tabla "+tablaname+" set: "+col1+" val: "+val1);
             File fichero = new File("/var/grupo7/"+tabla);                                          
          File aux = new File("/var/grupo7/"+tabla);
          String cadena="";
           try {
           FileInputStream fis = new FileInputStream(fichero);
           BufferedInputStream bis = new BufferedInputStream(fis);
           DataInputStream dis = new DataInputStream(bis);
                while (dis.available() != 0)  {
                cadena+=dis.readLine()+"\n";
                }
                 cadena+=""+val1+" | " +val2+" | "+val3+" | °";          
                fis.close();    bis.close();      dis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
          if(verifica_ex("/var/grupo7/"+tabla)){
          try {            
            PrintWriter fileOut = new PrintWriter(new FileWriter(aux, false));
            fileOut.write(cadena);
            fileOut.close();            
        } catch (FileNotFoundException ex) {           
        } catch (IOException ex) {           
        }                                        
          }else{          
           JOptionPane.showMessageDialog(null,"Tabla no existente");
          }


            }
///////////////////////////////////////////////////////////////////////  METODOS
            
            
public static void eliminar_campos(String tablename){
    
     File fichero = new File(tablename);
          File aux = new File(tablename);
          String cadena="";
           try {
           FileInputStream fis = new FileInputStream(fichero);
           BufferedInputStream bis = new BufferedInputStream(fis);
           DataInputStream dis = new DataInputStream(bis);
                cadena+=dis.readLine()+"\n";
                cadena+=dis.readLine()+"\n";                
                fis.close();    bis.close();      dis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
          if(verifica_ex(tablename)){
          try {            
            PrintWriter fileOut = new PrintWriter(new FileWriter(aux, false));
            fileOut.write(cadena);
            fileOut.close();            
        } catch (FileNotFoundException ex) {           
        } catch (IOException ex) {           
        }                              
          
          }else{          
           JOptionPane.showMessageDialog(null,"Tabla no existente");
          }
    


}            
public static void crear_frame_mostrar(int n_columnas,String tablaname){
    int conta=0;
    String[] columnas;
                DefaultTableModel mod = new DefaultTableModel();
                JTable tabla =new JTable(mod);
                Object[] etiquetas = new Object[n_columnas];
                String [] nombres=nombre_columnas(tablaname);
                 for(int i=0; i<n_columnas; i++)
                  {
                  etiquetas[i]=""+nombres[i].toString().trim();
                  }
                //CON NOMBRE LAS COLUMNAS
                  mod.setColumnIdentifiers(etiquetas);
                  while(mod.getRowCount()>0)
                  {
                  mod.removeRow(0);
                  }
                //LLENADO DE TABLA
             File leer = new File(tablaname+"");
            String cadena="";
            String auxcadena="";
            try {
                FileInputStream fis = new FileInputStream(leer);
                BufferedInputStream bis = new BufferedInputStream(fis);
                DataInputStream dis = new DataInputStream(bis);
                while (dis.available() != 0)  {
                cadena=dis.readLine();
                if(cadena.trim().equalsIgnoreCase("")){                
                }else{
                    Object[] datosF = new Object[n_columnas];
                    columnas = cadena.split("\\|");
                  for(int i=0; i<n_columnas; i++)
                  {
                   datosF[i]=""+columnas[i].toString().trim();                  
                  }
                    if(conta>1){
                        mod.addRow(datosF);
                        }
                 conta=conta+1;
                }                
                }                       
                fis.close(); bis.close(); dis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ventana(tabla);
}

public static void crear_frame_select(String columna,String tablaname){
    int conta=0;
    int n_columnas=1;
    int col_aux=-1;
    String[] columnas;

                DefaultTableModel mod = new DefaultTableModel();
                JTable tabla =new JTable(mod);
                Object[] etiquetas = new Object[n_columnas];                
                  etiquetas[0]=""+columna.trim();
                //CON NOMBRE LAS COLUMNAS
                  mod.setColumnIdentifiers(etiquetas);
                  while(mod.getRowCount()>0)
                  {
                  mod.removeRow(0);
                  }
                //LLENADO DE TABLA
            //JOptionPane.showMessageDialog(null,"llega");
            File leer = new File(tablaname+"");
            String cadena="";
            String auxcadena="";
            try {
                FileInputStream fis = new FileInputStream(leer);
                BufferedInputStream bis = new BufferedInputStream(fis);
                DataInputStream dis = new DataInputStream(bis);
                cadena=dis.readLine();
                columnas = cadena.split("\\|");
                for(int i=0; i<columnas.length; i++){
                    if(columna.equalsIgnoreCase(columnas[i].toString().trim())){                        
                    col_aux=i;
                    break;
                    }
                }
                if(col_aux!=-1){
                while (dis.available() != 0)  {
                cadena=dis.readLine();
                if(cadena.trim().equalsIgnoreCase("")){
                }else{
                    Object[] datosF = new Object[n_columnas];                     
                     columnas = cadena.split("\\|");
                     datosF[0]=""+columnas[col_aux].toString().trim();
                    if(conta>0){
                        mod.addRow(datosF);
                        }
                 conta=conta+1;
                }
                }
            
                fis.close(); bis.close(); dis.close();
                ventana(tabla);
            }else{
            JOptionPane.showMessageDialog(null,"Columna no existente");

            }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            
}



public static void ventana(JTable tabla){

    
                  JFrame vent;
                  vent=new JFrame();
                  JScrollPane scro;
                  scro = new JScrollPane(tabla);
                  vent.getContentPane().add(scro);
                  vent.pack();
                  vent.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
                  vent.setSize(500,350);
                  vent.setVisible(true);
}
public static boolean verifica_ex(String tabla){
        boolean esta=false;
                   try {
                        FileReader fileReader = new FileReader(tabla);
                        fileReader.close();
                        fileReader=null;
                        esta=true;
                    } catch (Exception ex) {
                            System.err.println(""+ex.getMessage().toString());
                            esta=false;
                            }
        return esta;
        }


public static int numero_columnas(String tabla){
int columnas=0;
String cadena="";
char cadaux;
            File leer = new File(tabla+"");
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            DataInputStream dis = null;             
            try {
                fis = new FileInputStream(leer);
                bis = new BufferedInputStream(fis);
                dis = new DataInputStream(bis);                
                cadena+=dis.readLine();
                for(int i=0; i<cadena.length(); i++)
                {
                    cadaux=cadena.charAt(i);
                    if(cadaux=='|'){
                    columnas=columnas+1;
                    }
                }                        
                fis.close();
                bis.close();
                dis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

return columnas;
}
public static String[] nombre_columnas(String tabla){
String[] columnas = null;
String cadena="";
            File leer = new File(tabla+"");
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            DataInputStream dis = null;
            try {
                fis = new FileInputStream(leer);
                bis = new BufferedInputStream(fis);
                dis = new DataInputStream(bis);
                cadena=dis.readLine();                
                columnas = cadena.split("\\|");
                fis.close();
                bis.close();
                dis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

return columnas;
}
}
